<?php
require_once 'Artdepot/Controller/Action.php';

class AccountController extends Artdepot_Controller_Action
{

    public function init()
    {
		parent::init();
	    if (!$this->auth->getIdentity ()) {
			$this->_redirect("/index/login");
			return;
		}
    }

    public function indexAction()
    {
    	//advertisements here
    	$adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
	    
    	$this->view->title = 'My Profile - ';
    	
    	$this->view->info = $this->auth->getIdentity();
    }
    
    public function favoriteAction() {
    	//advertisements here
    	$adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
	    
    	$this->view->title = 'My Favorite - ';
    	$favoriteTable = new Model_DbTable_CustomerFavorite();
    	$artworkTable = new Model_DbTable_ArtWork();
    	$favs = $favoriteTable->fetchAll('customer=' . $this->auth->getIdentity()->id . ' and type=\'artwork\'');
    	$favIds = array();
    	foreach ($favs as $fav) {
    		$favIds[] = $fav->target;
    	}
    	$favIds = join(",", $favIds);
    	$this->view->artworks = $artworks = $artworkTable->fetchAll($artworkTable->select()->where('id in(?)', $favIds));
    }
    
    public function addFavoriteAction() {
    	$this->_helper->layout->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	
    	$targetId = $this->_getParam('target', 0);
    	$type = $this->_getParam('type', 'artwork');
    	
		$message = 'Has been successfully favorite.';
    	
    	if (empty($targetId) || !in_array($type, array('artwork', 'artist'))) {
    		$message = 'Bad requrest.';
    	} else {
	    	$table = new Model_DbTable_CustomerFavorite();
	    	$row = $table->fetchRow($table->select()->where('target=?', $targetId)->where('customer=?', $this->auth->getIdentity()->id)->where('type=?', $type));
	    	if ($row) {
	    		$message = 'Already in your favorite.';
	    	} else {
	    		$row = $table->createRow();
	    		$row->target = $targetId;
	    		$row->type = $type;
	    		$row->customer = $this->auth->getIdentity()->id;
	    		$row->created_on = date('Y-m-d H:i:s');
	    		$row->save();
	    	}
    	}
    	
    	$message = array('message'=>$message);
    	$this->_helper->json($message);
    }
    
    public function removeFavoriteAction() {
    	$target = $this->_getParam('id', 0);
    	$type = $this->_getParam('type', 'artwork');
    	$table = new Model_DbTable_CustomerFavorite();
    	$row = $table->fetchRow($table->select()->where('target=?', $target)->where('customer=?', $this->auth->getIdentity()->id)->where('type=?', $type));
    	if ($row) {
    		$row->delete();
    	}
    	$this->_redirect('/account/favorite');
    }
    
	public function myOrdersAction() {
    	$this->view->title = 'My Orders - ';
    	$orderTable = new Model_DbTable_Order();
    	$orders = $orderTable->fetchAll('customer_id=' . $this->auth->getIdentity()->id, "status ASC");
    	
    	$username = explode(" ", $this->auth->getIdentity()->name);
    	if(!$username){
    		$this->view->firstName = $this->auth->getIdentity()->name;
    	}else{
    		$this->view->firstName = $username[0];
    		$this->view->lastName = $username[1];
    	}
    	
    	$messages = $this->_helper->flashMessenger->getMessages();
    	$this->view->message = $messages;
    	$this->view->orders = $orders;
    	$this->view->currentUser = $this->auth->getIdentity();
    	$this->logger->debug($messages);
    }
    
    public function addOrderAction(){
    	//advertisements here
    	$adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
	    
    	$this->view->title = 'Create Order - ';
    	$artworkId = (int) $this->_request->getParam("artworkId");
    	if($artworkId < 0){
    		$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    	}
    	
    	$table = new Model_DbTable_ArtWork();
    	$theArtWork = $table->fetchRow("id = $artworkId");
    	if (!$theArtWork){
    		$this->_redirect($this->_request->getServer('HTTP_REFERER'));
    	}
    	
    	$this->view->artwork = $theArtWork;
    	//$this->view->currentUser = $this->auth;
    	
    	$form = new Form_Order();
    	$form->getElement("artwork_id")->setValue($artworkId)->setLabel("")->setAttrib("style", "display:none");
    	$form->getElement("customer_id")->setValue($this->auth->getIdentity()->id)->setLabel("");
    	$form->removeElement("status");
    	$form->removeElement("good_num");
    	$form->removeElement("delivery_company");
    	$form->removeElement("delivery_date");
    	$form->getElement("currency")->setAttrib("onchange", "changePrice();");
    	$form->getElement("price")->setAttrib("readonly", "readonly");
    	$form->getElement("tell")->setValue($this->auth->getIdentity()->tell);
    	$form->getElement("mobile")->setValue($this->auth->getIdentity()->mobile);
    	$form->getElement("state")->setValue($this->auth->getIdentity()->state);
    	$form->getElement("address")->setValue($this->auth->getIdentity()->address);
    	$form->getElement("city")->setValue($this->auth->getIdentity()->city);
    	$form->getElement("country")->setValue($this->auth->getIdentity()->country);
    	$form->getElement("zipcode")->setValue($this->auth->getIdentity()->zipcode);
    	$form->getElement("receiver")->setValue($this->auth->getIdentity()->name);
    	//$form->getElement("delivery_type")->setValue();
    	$form->removeElement("delivery_cost");
    	//$form->getElement("message")->setValue();
    	if($this->_request->isPost()){
    		if($form->isValid($this->_request->getParams())){
    			$table = new Model_DbTable_Order();
    			$values = $form->getValues();
    			$values["id"] = 0;
    			$values["artwork_id"] = $artworkId;
    			$values["customer_id"] = $this->auth->getIdentity()->id;
    			$values["status"] = "pending";
    			if($values["currency"] == "USD"){
    				$values["price"] = $theArtWork->usd_price;
    			}elseif($values["currency"] == "EUR"){
    				$values["price"] = $theArtWork->uro_price;
    			}else{
    				throw new Zend_Exception("Wrong currency!!");
    			}
    			
    			$values["status"] = "pending";
    			$values["created_on"] = date("Y-m-d H:i:s");
    			$values["updated_on"] = date("Y-m-d H:i:s");
    			$values["delivery_cost"] = 0;
    			
    			$table->insert($values);
    			$this->sendOrderEmail($this->auth->getIdentity(),$theArtWork);
    			$this->_helper->flashMessenger("Your message has been sent. We will contact you by e-mail within 12 hours.");
    			$this->_redirect("/account/my-orders/");
    		}
    	}
    	
    	
    	$this->view->form = $form;
    	
    }
    
	public function sendOrderEmail($userInfo, $artwork){
    	$salesEmail = "sales@artdepot.cn";
    	$emailTitle = "Notice, new order for artwork " . $artwork->name . ".";
    	$emailContent = <<<EOF
    	Dear,
    		a new order comes for artwork {$artwork->name}, please confirm, here is the link to the order list:
    		<a href="http://www.artdepot.cn/admin/manage-order/" target="_blank">http://www.artdepot.cn/admin/manage-order/</a>
EOF;
		$mail = new Zend_Mail();
		$mail->setBodyHtml($emailContent)
			->setSubject($emailTitle)
			->setFrom("admin@artdepot.cn", "system admin")
			->addTo($salesEmail)
			->send();
    }
    
    public function changeProfileAction(){
    	//advertisements here
    	$adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
	    
    	$this->view->title = 'Edit My Profile - ';
    	$form = new Form_Customer();
    	$form->getElement("email")->setAttrib("readonly", "readonly");
    	if ($this->_request->isPost()){
    		if ($form->isValid($this->_request->getParams())){
    			$values = $form->getValues();
    			
    			if ($this->auth->getIdentity()->id != $values["id"]){
    				throw new Zend_Exception("you are not going to success anything...");
    			}else{
    				$table = new Model_DbTable_Customer();
	    			$currentUser = $table->fetchRow("id = " . $this->auth->getIdentity()->id);
	    			$currentUser->setFromArray($values)->save();
	    			$infor = $currentUser->toArray();
	    			unset($infor["passwd"]);
	    			
	    			$this->auth->getStorage()->clear();
	    			$this->auth->getStorage()->write((object)$infor);
	    			$this->_redirect("/account/");
    			}
    		}
    	}else{
    		$form->setDefaults((array) $this->auth->getIdentity());
    	}
    	
    	
    	
    	$this->view->form = $form;
    }
    
    public function changePasswordAction(){
    	//advertisements here
    	$adTable = new Model_DbTable_Advertisement(); 
	    $this->view->ads = $adTable->fetchAll("position = 0 and enabled = 1", "display_order ASC");
	    
    	$this->view->title = 'Change My Password - ';
    	$form = new Form_ChangePassword();
    	$form->getElement("id")->setValue($this->auth->getIdentity()->id);
    	if ($this->_request->isPost()){
    		if ($form->isValid($this->_request->getParams())){
    			$values = $form->getValues();
    			if ($this->auth->getIdentity()->id != $values["id"]){
    				throw new Zend_Exception("whose password are you modifying??");
    			}else{
    				$table = new Model_DbTable_Customer();
    				$theCustomer = $table->fetchRow("id = " . $this->auth->getIdentity()->id );
    				$theCustomer->passwd = md5($values["passwd"]);
    				$theCustomer->save();
    				$this->view->message = "Your password has been changed.";
    			}
    		}
    	}
    	
    	$this->view->form = $form;
    }
    

	public function addScoreAction() {
    	$this->_helper->layout->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	
    	$artistId = $this->_getParam('id', 0);
    	$score = intval($this->_getParam('score', 5));
    	
		$message = 'Thanks for joinning the appraisal!';
    	
    	if (empty($artistId) || empty($score)) {
    		$message = 'Bad request.';
    	} else {
	    	$table = new Model_DbTable_ArtistScoreHistory();
	    	$row = $table->fetchRow($table->select()->where('artist=?', $artistId)->where('customer=?', $this->auth->getIdentity()->id));
	    	if ($row) {
	    		$message = 'You have joined appraisal to this artist before.';
	    	} else {
	    		$row = $table->createRow();
	    		$row->artist = $artistId;
	    		$row->score = $score;
	    		$row->customer = $this->auth->getIdentity()->id;
	    		$row->created_on = date('Y-m-d H:i:s');
	    		$row->save();
	    		
	    		$allScores = $table->fetchAll("artist=$artistId");
		    	
	    		$joinedUserCount = 0;
				$score = 0;
				foreach ($allScores as $s) {
					$joinedUserCount++;
					$score += $s->score;
				}
				if ($joinedUserCount>0) {
					$score = ceil($score/$joinedUserCount);
				} else {
					$score = 5;
				}
				
				$artistTable = new Model_DbTable_Artist();
				$theArtist = $artistTable->fetchRow("id = $artistId");
				$theArtist->score = $score;
				$theArtist->save();
				
	    	}
	    	
    	}
    	
    	$message = array('message'=>$message);
    	$this->_helper->json($message);
   		
	}
	
	public function browsedPagesAction(){
    	$historyTable = new Model_DbTable_BrowseHistory(); 
    	$userId = $this->auth->getIdentity()->id;
	    $this->view->pages = $historyTable->fetchAll("user_id = $userId", "browse_time DESC", 20);
	    
    	$this->view->title = 'My browsed pages - ';
		
	}
}

